package com.stu.aq;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Locale;

import android.content.Context;
import android.os.Environment;

public class Log {
	private static File file;
	private static OutputStream out;
	private static SimpleDateFormat format;

	public static void open( Context c ) {
		if( out == null ) {
			format = new SimpleDateFormat( "kk:mm:ss", Locale.US );
			if( Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ) {
				file = new File( c.getExternalFilesDir(null), "log" );
				file.mkdirs();
				try {
					file = new File(file, "log.html");
					out = new BufferedOutputStream( new FileOutputStream(file) );
					String s = "<!DOCTYPE html>\n<html>\n<body><code>\n";
					out.write( s.getBytes() );
				} catch( Exception e ) {
					android.util.Log.e("log", "open", e);
				}
			}
		}
	}
	
	public static void close() {
		if( out != null ) {
			try {
				String s = format.format(System.currentTimeMillis()) + " Log Closed<br>\n";
				s += "</code></body>\n</html>\n";
				out.write( s.getBytes() );
				out.close();
				out = null;
			} catch( Exception e ) {
			}
		}
	}
		
	public static void d( String s1, String s2 ) {
		if( AQ.LOGCAT )
			android.util.Log.d( s1, s2 );
		else if( out != null ) {
			String s = format.format(System.currentTimeMillis()) + " " + s1 + ": " + s2 + "<br>\n";
			try {
				out.write( s.getBytes() );
			} catch( Exception e ) {
			}
		}
	}
	
	public static void d( String s1, String s2, Throwable e ) {
		if( AQ.LOGCAT )
			android.util.Log.d( s1, s2, e );
		else if( out != null ) {
			String s = format.format(System.currentTimeMillis()) + " " + s1 + ": " + s2 + " " + e + "<br>\n";
			try {
				out.write( s.getBytes() );
			} catch( Exception ex ) {
			}
		}
	}
	public static void e( String s1, String s2 ) {
		if( AQ.LOGCAT )
			android.util.Log.e( s1, s2 );
		else if( out != null ) {
			String s = format.format(System.currentTimeMillis()) + " Error: " + s1 + ": " + s2 + "<br>\n";
			try {
				out.write( s.getBytes() );
			} catch( Exception e ) {
			}
		}
	}
	public static void w( String s1, String s2 ) {
		if( AQ.LOGCAT )
			android.util.Log.w( s1, s2 );
		else if( out != null ) {
			String s = format.format(System.currentTimeMillis()) + " Warning: " + s1 + ": " + s2 + "<br>\n";
			try {
				out.write( s.getBytes() );
			} catch( Exception e ) {
			}
		}
	}
}
